#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Computer
{
public:
    Computer(const char * brand,double price)
    : _brand(new char[strlen(brand) + 1]())
    , _price(price)
    {
        cout << "Computer(const char *,double)" << endl;
        strcpy(_brand,brand);
    }
 
    Computer(const Computer & rhs)
    : _brand(new char[strlen(rhs._brand) + 1]())
    , _price(rhs._price)
    {
        strcpy(_brand,rhs._brand);//进行深拷贝
        cout << "Computer(const Computer &)" << endl;
    }

    Computer & operator=(const Computer & rhs){
        cout << "赋值运算符函数" << endl;
        if(this != &rhs){//1.考虑自复制情况
            delete [] _brand; //2.回收本对象的数据成员原本管理的堆空间
            _brand = new char[strlen(rhs._brand) + 1]();//3.深拷贝
            strcpy(_brand,rhs._brand);
            _price = rhs._price;//对其他的数据成员完成赋值
        }
        return *this;//4.返回本对象
    }


    void print() 
    {
        cout << "brand:" << _brand << endl;
        cout << "price:" << _price << endl;
    }

    ~Computer(){
        cout << "~Computer()" << endl;
        if(_brand){
            delete [] _brand;
            _brand = nullptr;//安全回收
        }
    }
private:
    char * _brand;
    double _price;
};


void test0(){
    /* int a = 1, b = 2, c = 3; */
    /* cout << &a << endl; */
    /* cout << &(a = b = c) << endl; */
    /* cout << a << endl; */
    /* cout << b << endl; */
    /* cout << c << endl; */


    Computer pc("huawei",7000);
    Computer pc2("apple",20000);
    Computer pc3("lenovo",8000);
    Computer pc4  = pc3;//拷贝构造调用
    /* pc2 = pc2; //自复制 */
    //赋值运算符函数调用
    pc2 = pc;
    pc = Computer("A",6000);
    /* pc3 = pc2 = pc; */
    pc2.print();
}

int main(void){
    test0();
    return 0;
}
